﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using XFABManager;
using XFGameFramework.Localization;

public class EditLanguageInfoWindow : EditorWindow
{  
    private MultiLanguageConfigs multiLanguageConfigs;

    private LanguageConfig languageConfig;

    private LanguageInfo languageInfo;

    private Dictionary<int, GUIContent> projectNameGUIContent = new Dictionary<int, GUIContent>();

    private GUIContent iconImageContent; 

    private GUIStyle textFieldStyle;

    private GUIStyle labelStyle;

    private Vector2 scrollPosition;

#if UNITY_6000_2_OR_NEWER
    private TreeViewItem<int> treeViewItem;
#else
    private TreeViewItem treeViewItem;
#endif

#if UNITY_6000_2_OR_NEWER 
    public void ShowLanguageInfo(MultiLanguageConfigs multiLanguageConfigs,LanguageConfig languageConfig, LanguageInfo languageInfo, TreeViewItem<int> treeViewItem)
#else
    public void ShowLanguageInfo(MultiLanguageConfigs multiLanguageConfigs,LanguageConfig languageConfig, LanguageInfo languageInfo, TreeViewItem treeViewItem)
#endif

    {
        this.multiLanguageConfigs = multiLanguageConfigs;
        this.languageConfig = languageConfig;
        this.languageInfo = languageInfo;
        this.treeViewItem = treeViewItem;
    }

    private void OnGUI()
    {
        if (languageConfig == null || languageInfo == null)
        {
            Close();
            return;
        }

        scrollPosition = GUILayout.BeginScrollView(scrollPosition);

        OnGUI_ID();

        OnGUI_Type();

        OnGUI_Value();

        OnGUI_Remark();

      

        EditorGUI.BeginDisabledGroup(languageInfo.type != MultiLanguageType.String || multiLanguageConfigs.Languages.Count <= 1);

        GUILayout.Space(5);

        if (GUILayout.Button("翻译"))
        {
            EditorWindow.GetWindow<TranslateLanguageInfoWindow>().ShowLanguageInfo(multiLanguageConfigs, languageConfig, languageInfo);
        }

        EditorGUI.EndDisabledGroup();


        OnGUI_Edit();

        OnGUI_Use();



        GUILayout.EndScrollView();
    }

    private void OnGUI_ID() 
    {
        GUILayout.Space(3);

        EditorGUI.BeginChangeCheck();
        EditorGUILayout.LabelField(string.Empty, "ID(唯一标识)", "BoldLabel");
        int id = EditorGUILayout.DelayedIntField("ID",languageInfo.id);
        if (EditorGUI.EndChangeCheck())
        {
            if (id < 0)
            {
                ShowNotification(new GUIContent(string.Format("id:{0}不能小于0!", id))); 
            }
            else
            {
                if (!MultiLanguageConfigsController.IsContainID(id))
                {
                    // 修改其他语言的id 
                    foreach (var item in multiLanguageConfigs.Languages)
                    {
                        LanguageInfo info = item.GetLanguageInfo(languageInfo.id);

                        if (info == null) continue;
                        info.id = id;
                        item.ClearCache();
                        item.Save();
                    }

                    AssetDatabase.SaveAssets();
                }
                else
                {
                    ShowNotification(new GUIContent(string.Format("id:{0}已经存在!", id)));
                }
            }

            
        }
    }


    private void OnGUI_Type() 
    {
        GUILayout.Space(3);

        EditorGUI.BeginChangeCheck();
        EditorGUILayout.LabelField(string.Empty, "类型", "BoldLabel");
        languageInfo.type = (MultiLanguageType)EditorGUILayout.EnumPopup("type",languageInfo.type);
        if (EditorGUI.EndChangeCheck())
        {
            // 修改其他语言的类型
            foreach (var item in multiLanguageConfigs.Languages)
            { 
                if(item == languageConfig) continue;
                LanguageInfo i = item.GetLanguageInfo(languageInfo.id);
                i.type = languageInfo.type;
                item.Save();
            }

            languageConfig.Save();
        }
    }


    private void OnGUI_Value() 
    {

        if (textFieldStyle == null)
        {
            textFieldStyle = new GUIStyle(GUI.skin.textField);
            textFieldStyle.wordWrap = true;
        }


        GUILayout.Space(3);

        EditorGUILayout.LabelField(string.Empty, "值", "BoldLabel");

        switch (languageInfo.type)
        {
            case MultiLanguageType.String:
                 
                EditorGUI.BeginChangeCheck();

                GUILayout.BeginHorizontal();

                EditorGUILayout.LabelField("str",GUILayout.Width(148));

                languageInfo.str = EditorGUILayout.TextArea(languageInfo.str, textFieldStyle);
                
                GUILayout.EndHorizontal();

                if (EditorGUI.EndChangeCheck())
                    languageConfig.Save();

                break;
            case MultiLanguageType.Image:
                  
                if (!projectNameGUIContent.ContainsKey(languageInfo.id))
                    projectNameGUIContent.Add(languageInfo.id, new GUIContent());

                XFABProject project = XFABProjectManager.Instance.GetProject(languageInfo.image.projectName);

                if (project == null)
                    languageInfo.image.projectName = string.Empty;

                projectNameGUIContent[languageInfo.id].text = project == null ? "空" : project.name;
                projectNameGUIContent[languageInfo.id].tooltip = "资源模块名称";

                GUILayout.BeginHorizontal();

                GUILayout.BeginVertical();

                GUILayout.BeginHorizontal();

                EditorGUILayout.LabelField("projectName",GUILayout.Width(148));

                if (EditorGUILayout.DropdownButton( projectNameGUIContent[languageInfo.id], FocusType.Passive))
                {
                    // 选择 
                    List<XFABProject> projects = XFABProjectManager.Instance.Projects;

                    GenericMenu menu = new GenericMenu();

                    if (projects == null || projects.Count == 0)
                    {
                        menu.AddDisabledItem(new GUIContent("无"));
                        menu.AddSeparator(string.Empty);

                        menu.AddItem(new GUIContent("创建资源模块"), false, () =>
                        {
                            Rect r = new Rect(0, 0, 600, 700);
                            XFAssetBundleManagerCreate window = EditorWindow.GetWindowWithRect<XFAssetBundleManagerCreate>(r, true, "创建项目");
                            window.Show();
                        });
                    }
                    else
                    {
                        foreach (var item in projects)
                        {
                            menu.AddItem(new GUIContent(item.name), project == item, () =>
                            {
                                languageInfo.image.projectName = item.name;
                                languageConfig.Save();
                            });
                        }
                    }

                    menu.ShowAsContext();
                }

                GUILayout.EndHorizontal();


                EditorGUI.BeginChangeCheck();
                languageInfo.image.imageName = EditorGUILayout.TextField("imageName", languageInfo.image.imageName);
                if (EditorGUI.EndChangeCheck())
                {
                    iconImageContent = null;
                    languageConfig.Save();
                }

                if (iconImageContent == null)
                {
                    iconImageContent = new GUIContent(EditorGUIUtility.IconContent("BuildSettings.Broadcom"));

                    Texture texture = LanguageConfigsInspector.GetImage(languageInfo.image.projectName, languageInfo.image.imageName);

                    if (texture != null)
                        iconImageContent.image = texture;
                    else
                        iconImageContent.tooltip = string.Format("图片{0}/{1}加载失败,请检查名称是否正确，或是否添加到资源模块?", languageInfo.image.projectName, languageInfo.image.imageName);
                }
                 
                GUILayout.EndVertical();

                if (GUILayout.Button( iconImageContent,GUILayout.Width(40),GUILayout.Height(40)))
                {
                    EditorGUIUtility.PingObject(iconImageContent.image);
                     
                    iconImageContent = null;
                }
               
                GUILayout.EndHorizontal();

                break;
            case MultiLanguageType.NetworkImage:

                EditorGUI.BeginChangeCheck();

                GUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("url", GUILayout.Width(148));
                languageInfo.url = EditorGUILayout.TextArea(languageInfo.url, textFieldStyle);
                
                GUILayout.EndHorizontal();
                
                if (EditorGUI.EndChangeCheck())
                    languageConfig.Save();

                break;
        }

    }


    private void OnGUI_Remark() 
    {
        GUILayout.Space(3); 
        EditorGUILayout.LabelField(string.Empty, "备注", "BoldLabel"); 

        EditorGUI.BeginChangeCheck();

        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("notes",GUILayout.Width(148));

        if (textFieldStyle == null) {
            textFieldStyle = new GUIStyle(GUI.skin.textField);
            textFieldStyle.wordWrap = true;
        }

        languageInfo.notes = EditorGUILayout.TextArea(languageInfo.notes, textFieldStyle);
        GUILayout.EndHorizontal();

        if(EditorGUI.EndChangeCheck())
            languageConfig.Save();
    }


    private void OnGUI_Edit()
    {

        GUILayout.FlexibleSpace();

        GUILayout.Space(3);

        if (labelStyle == null)
        {
            labelStyle = new GUIStyle(GUI.skin.label);
            labelStyle.wordWrap = true;
            labelStyle.richText = true;
            labelStyle.alignment = TextAnchor.UpperLeft;
        }
         
            EditorGUI.BeginDisabledGroup(true);
            GUILayout.Label("当前编辑的语言", "BoldLabel");
            EditorGUI.EndDisabledGroup();
         
            GUILayout.BeginHorizontal();

            EditorGUILayout.SelectableLabel(languageConfig.language.ToString(), labelStyle, GUILayout.Width(148));


            switch (languageInfo.type)
            {
                case MultiLanguageType.String:
                    EditorGUILayout.SelectableLabel(languageInfo.str, labelStyle, GUILayout.Height(100));
                    break;
                case MultiLanguageType.Image:
                    if (string.IsNullOrEmpty(languageInfo.image.projectName) && string.IsNullOrEmpty(languageInfo.image.imageName))
                    {
                        EditorGUILayout.SelectableLabel("空");
                    }
                    else
                    {
                        EditorGUILayout.SelectableLabel(string.Format("{0}/{1}", languageInfo.image.projectName, languageInfo.image.imageName));
                    }
                    break;
                case MultiLanguageType.NetworkImage:
                    EditorGUILayout.SelectableLabel(languageInfo.url, labelStyle);
                    break;
            }


            GUILayout.EndHorizontal();
       
    }


    private void OnGUI_Use() 
    { 

        //GUILayout.FlexibleSpace();

        GUILayout.Space(3);

        if (labelStyle == null) {
            labelStyle = new GUIStyle(GUI.skin.label);
            labelStyle.wordWrap = true;
            labelStyle.richText = true;
            labelStyle.alignment = TextAnchor.UpperLeft;
        }


        LanguageConfig language = multiLanguageConfigs.GetLanguageConfigData(LocalizationManager.Language);

        if (language != null) 
        {
            EditorGUI.BeginDisabledGroup(true);
            GUILayout.Label("当前使用的语言", "BoldLabel");
            EditorGUI.EndDisabledGroup();

            LanguageInfo info = language.GetLanguageInfo(languageInfo.id);

            GUILayout.BeginHorizontal();

            EditorGUILayout.SelectableLabel(LocalizationManager.Language.ToString(), labelStyle, GUILayout.Width(148));

              
            switch (info.type)
            {
                case MultiLanguageType.String: 
                    EditorGUILayout.SelectableLabel(info.str, labelStyle,GUILayout.Height(100)); 
                    break;
                case MultiLanguageType.Image:
                    if (string.IsNullOrEmpty(info.image.projectName) && string.IsNullOrEmpty(info.image.imageName))
                    {
                        EditorGUILayout.SelectableLabel("空");
                    }
                    else
                    {
                        EditorGUILayout.SelectableLabel(string.Format("{0}/{1}", info.image.projectName, info.image.imageName));
                    }
                    break;
                case MultiLanguageType.NetworkImage:
                    EditorGUILayout.SelectableLabel(info.url, labelStyle);
                    break;
            }
             

            GUILayout.EndHorizontal();
        }
    }
     
    private void OnDisable()
    {
        AssetDatabase.Refresh();
        AssetDatabase.SaveAssets(); 
    }


    private void OnLostFocus()
    {
        LanguageInfoTreeViewItem item = this.treeViewItem as LanguageInfoTreeViewItem;

        if (item != null)
            item.UpdateDisplayName(); 
    }


    [InitializeOnLoadMethod]
    static void InitializeOnLoadMethod()
    {
        if (HasOpenInstances<EditLanguageInfoWindow>())
        {
            EditorApplication.delayCall += () => {
                GetWindow<EditLanguageInfoWindow>().Close(); 
            };
        }

    }

}
